﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Linq;
using System.Web;
using System.Text;
using System.Text.Json;

using System.Security.Cryptography;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Net.Sockets;
using System.Threading;

using System.Net.Http.Headers;
using System.Net.Mail;
using System.Security.Policy;
using System.Security.Cryptography.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using System.Reflection.PortableExecutable;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Components.Routing;
using Kingdee.SDK.com.kingdee.service.data.api;
using Kingdee.SDK.Client;
using Kingdee.SDK.com.kingdee.service.data.entity;
using System.DirectoryServices.ActiveDirectory;
using System.Net.NetworkInformation;




namespace GnpFine.Application.NmpaSystem
{
    /// <summary>
    /// 云星辰的单据查询接口
    /// </summary>
    public class KdStartSdkUtil
    {
        private SalOutBoundApi salOutBoundInstance = null;
        private PurInboundApi purInboundApiInstance = null;
        private MaterialApi materialApiInstance = null;
        private InventoryApi inventoryApiInstance = null;

        public KdStartSdkUtil()
        {
            initToken();
        }



        /// <summary>
        /// 获取销售订单列表
        /// 因为分页限制，循环调用获取所有数据。
        /// </summary>
        public ResponseModel<InstrumentSale> GetKdSaleList()
        {
            // 一、预查询 获取销售订单列表api接口 ---分页
            var billListRows = new List<SalOutBoundListReplyRow>();

            if (salOutBoundInstance != null)
            {
                int page = 1;
                while (true)
                {
                    var billListPage = salOutBoundInstance.SalOutBoundList(new SalOutBoundListReq()
                    {
                        EndBillDate = "2024-01-31",
                        Page = page.ToString(),
                        PageSize = "1000",
                        StartBillDate = "2024-01-01",

                    });

                    if (billListPage.Rows.Count > 0)
                    {
                        billListRows.AddRange(billListPage.Rows);
                    }

                    if (billListPage.PageSize == billListPage.Page)
                        break;
                    else
                        page = page + 1;
                }

            }


            // 二 、 获取单据明细 并组装数据成药监要求格式
            List<InstrumentSale> islist = new List<InstrumentSale>();

            foreach (var billListRow in billListRows)
            {
                var billDetail = salOutBoundInstance.SalOutBoundDetail(null,billListRow.BillNo);
         
                foreach (var billDetailEntity in billDetail.MaterialEntity)
                {
                    islist.Add(new InstrumentSale()
                    {
                        SALE_NO = billDetail.BillNo,
                        SALE_DATE = DateTime.Parse(billDetail.BillDate),
                        INSTRUMENT_CODE = billDetailEntity.MaterialNumber,
                        INSTRUMENT_NAME = billDetailEntity.MaterialName,
                        REGIST_NO = billDetailEntity.CustomEntityField["custom_field__3__3uhw16utmc8i"],
                        BATCH_NO = billDetailEntity.BatchNo,
                        VALIDITY = DateTime.Parse(billDetailEntity.ValidDate),
                        PRODUCER = billDetailEntity.CustomEntityField["custom_field__3__3uhw2mvfg7m9"],
                        SPEC = billDetailEntity.MaterialModel,
                        UNIT = billDetailEntity.UnitName,
                        QTY = Convert.ToDecimal(billDetailEntity.Qty),
                        PURCHASER_NAME = billListRow.CustomerName,
                        PURCHASER_CODE = billListRow.CustomerNumber,
                        DESTROY_NO = ""
                    });
                }
            }

            ResponseModel<InstrumentSale> tmp3 = new ResponseModel<InstrumentSale>(false, "失败");
            tmp3.data = islist;
            tmp3.success = true;
            tmp3.message = "成功";
            return tmp3;

        }


        /// <summary>
        /// 获采购列表
        /// 因为分页限制，循环调用获取所有数据。
        /// </summary>
        public ResponseModel<InstrumentStock> GetKdPurchaseList()
        {
            // 一、预查询 获取销售订单列表api接口 ---分页
            var billListRows = new List<InboundListReplyOrderList>();

            if (purInboundApiInstance != null)
            {
                int page = 1;
                while (true)
                {
                    var billListPage = purInboundApiInstance.PurInboundList(new PurInboundListReq()
                    {
                        EndBillDate = "2024-01-31",
                        Page = page.ToString(),
                        PageSize = "1000",
                        StartBillDate = "2024-01-01",

                    });

                    if (billListPage.Rows.Count > 0)
                    {
                        billListRows.AddRange(billListPage.Rows);
                    }

                    if (billListPage.PageSize == billListPage.Page)
                        break;
                    else
                        page = page + 1;
                }

            }


            // 二 、 获取单据明细 并组装数据成药监要求格式
            List<InstrumentStock> islist = new List<InstrumentStock>();

            foreach (var billListRow in billListRows)
            {
                var billDetail = salOutBoundInstance.SalOutBoundDetail(null, billListRow.BillNo);

                foreach (var billDetailEntity in billDetail.MaterialEntity)
                {
                    islist.Add(new InstrumentStock()
                    {
                        BUY_NO = billDetail.BillNo,
                        PURCHASE_DATE = DateTime.Parse(billDetail.BillDate),
                        INSTRUMENT_CODE = billDetailEntity.MaterialNumber,
                        INSTRUMENT_NAME = billDetailEntity.MaterialName,
                        REGIST_NO = billDetailEntity.CustomEntityField["custom_field__3__3uhw16utmc8i"],
                        BATCH_NO = billDetailEntity.BatchNo,
                        VALIDITY = DateTime.Parse(billDetailEntity.ValidDate),
                        PRODUCER = billDetailEntity.CustomEntityField["custom_field__3__3uhw2mvfg7m9"],
                        SPEC = billDetailEntity.MaterialModel,
                        UNIT = billDetailEntity.UnitName,
                        QTY = Convert.ToDecimal(billDetailEntity.Qty),
                        PROVIDER_NAME = billListRow.SupplierName,
                        PROVIDER_CODE = billListRow.SupplierNumber,
                        DESTROY_NO = ""
                    });
                }
            }

            ResponseModel<InstrumentStock> tmp3 = new ResponseModel<InstrumentStock>(false, "失败");
            tmp3.data = islist;
            tmp3.success = true;
            tmp3.message = "成功";
            return tmp3;

        }



        /// <summary>
        /// 及时库存的获取
        /// </summary>
        /// <param name="para"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        public ResponseModel<InstrumentStore> GetKdInvData(string para, string enddate)
        {

            //  一 、获取物料数据,灭用，
/*            var MaterialList = new List<MaterialListReplyRow>();

            if (materialApiInstance != null)
            {
                int page = 1;
                int totalpage = 1;
                while (page <= totalpage)
                {
                    var billListPage = materialApiInstance.MaterialMaterialList(new MaterialMaterialListReq()
                    {
                        Page = page.ToString(),
                        PageSize = "1000",
                    });

                    MaterialList.AddRange(billListPage.Rows);
                    totalpage = (int)billListPage.TotalPage;
                    page = (int)billListPage.Page;

                }

            }*/


            //  二 、获取库存数据
            var inventoryList = new List<InvListResRow>();

            if (materialApiInstance != null)
            {
                int page = 1;
                int totalpage = 1;
                while (page <= totalpage)
                {
                    var billListPage = inventoryApiInstance.InventoryInvList(new InventoryInvListReq()
                    {
                        Page = page,
                        PageSize = 1000,
                    });

                    inventoryList.AddRange(billListPage.Rows);
                    totalpage = (int)billListPage.TotalPage;
                    page = (int)billListPage.Page;

                }

            }


            // 三 、 获取单据明细 并组装数据
            List<InstrumentStore> islist = new List<InstrumentStore>();
            foreach (var kdise in inventoryList)
            {
                // 获取物料明细
                var mt  = materialApiInstance.MaterialMaterialDetail(null,kdise.MaterialNumber);

                islist.Add(new InstrumentStore()
                {
                    INSTRUMENT_CODE = kdise.MaterialNumber,
                    INSTRUMENT_NAME = kdise.MaterialName,
                    REGIST_NO = mt.CustomField["kkk"],
                    BATCH_NO = kdise.BatchNo,
                    VALIDITY = DateTime.Parse(kdise.ValidDate),
                    PRODUCER = mt.CustomField["ytu"],
                    SPEC = kdise.MaterialModel,
                    UNIT = mt.BaseUnitName,
                    QTY = Convert.ToDecimal(kdise.Qty),
                    DESTROY_NO = ""
                });
                
            }


            ResponseModel<InstrumentStore> tmp3 = new ResponseModel<InstrumentStore>(false, "失败");
            tmp3.data = islist;
            tmp3.success = true;
            tmp3.message = "成功";
            return tmp3;

        }



        /// <summary>
        /// 认证获取token
        /// </summary>
        /// <returns></returns>
        private void initToken()
        {
            string ClientID = "268149";
            string ClientSecret = "d57710a947f43ae6c2f0d4d57b1a5a0c";
            string outerInstanceId = "227496776318455808";

            Configuration cfg = new Configuration()
            {
                ClientId = ClientID,
                ClientSecret = ClientSecret,
            };


            // 获取账套信息、AccountId、AccountName、 AgreementCompanyName
            //AppKey、AppSecret、ClientId、Domain、GroupName、OuterInstanceId、ServiceId、Status
            AuthorizeApi authorizeApi = new AuthorizeApi(cfg);
            var authorList = authorizeApi.AsterAuthorize(outerInstanceId);//此参数替换成自己的


            var appKey = authorList.First().AppKey;
            var appSecret = authorList.First().AppSecret;
            string appSignature = SHAHelper.HmacSHA256(appSecret, appKey);

            //这里取产品的appToken
            AppTokenApi appTokenApi = new AppTokenApi(cfg);
            AsterAppTokenRes asterAppTokenRes = appTokenApi.AsterAppToken(appKey, appSignature, null);
            // 保存AppToken ，有效期为24小时，过期后重新获取
            cfg.AppToken = asterAppTokenRes.AppToken;


            //## 步骤四：使用.NET SDK 调用业务接口
            //例如，调用一个科目列表API方法：
            //使用配置文件创建一个业务对象

            salOutBoundInstance = new SalOutBoundApi(cfg);
            purInboundApiInstance = new PurInboundApi(cfg);
            materialApiInstance = new MaterialApi(cfg);
            inventoryApiInstance = new InventoryApi(cfg);


        }


    }
    
} 

